package com.eqxiu.gateway.user;

import com.alibaba.fastjson.JSONObject;
import com.eqxiu.dubbo.DubboUtil;
import com.eqxiu.js.JavaScriptProvider;
import com.eqxiu.user.api.UserApi;
import com.eqxiu.user.api.dto.User;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.maple.util.common.JsonUtil;
import jdk.nashorn.internal.ir.annotations.Reference;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
import net.sf.ehcache.config.CacheConfiguration;
import net.sf.ehcache.config.Configuration;
import org.jboss.netty.handler.codec.http.Cookie;
import org.jboss.netty.handler.codec.http.CookieDecoder;
import org.jboss.netty.handler.codec.http.QueryStringDecoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class GatewayLogUtil {

    private static final Logger logger = LoggerFactory.getLogger(GatewayLogUtil.class);

    public static CacheManager cacheManager;
    public static Cache sessionUserCache;

    public static void initCache() {
        System.out.println("初始化缓存配置...");
        Configuration config = new Configuration();
        CacheConfiguration cacheConfig = new CacheConfiguration();
        cacheConfig.setName("session_user_cache_dubbo");
        cacheConfig.setMaxEntriesLocalHeap(1000000);
        cacheConfig.setMaxEntriesLocalDisk(10000000);
        cacheConfig.setTimeToLiveSeconds(86400);
        cacheConfig.setMemoryStoreEvictionPolicy("LRU");
        cacheConfig.setDiskPersistent(true);
        cacheConfig.setDiskSpoolBufferSizeMB(1024);
        config.addCache(cacheConfig);
        cacheManager = CacheManager.create(config);
        sessionUserCache = cacheManager.getCache("session_user_cache_dubbo");
    }

    /**
     * 用session获取用户信息
     *
     * @param session_id
     * @return
     */

    public static User getUserInfo(String session_id) {

        User userInfo = new User();
        try {
            if (session_id == null) {
                return null;
            }

            session_id = session_id.trim();

            if ("-".equals(session_id) || "".equals(session_id) || "null".equalsIgnoreCase(session_id)) {
                return null;
            }

            // 根据session id获取用户信息：
            // 先从缓存中获取，如果没有，则调用接口查询，添加到缓存中
            // 如果接口查询结果没有信息，则不缓存
            Element userInfoElement = sessionUserCache.get(session_id);
            if (userInfoElement == null) {
                if (DubboUtil.userApi != null) {
                    String userId = DubboUtil.userApi.getUserIdBySessionId(session_id);

                    if (userId == null) {
                        logger.warn("DubboUtil.userApi.getUserIdBySessionId("+session_id+") 获取用户id为空");
                        return null;
                    }
                    userInfo.setId(userId);
//                    logger.info("DubboUtil.userApi.getUserBySessionId("+session_id+") "+userId);
                    userInfoElement = new Element(session_id, userId);
                    sessionUserCache.put(userInfoElement);
//                    logger.info("now the  sessionUserCache length is "+ sessionUserCache.getSize());
                }
            } else {
                String userId = (String) userInfoElement.getObjectValue();
                userInfo.setId(userId);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return userInfo;
    }

    /**
     * 直接从cookie中获取用户id
     * @param originalRecord
     * @return
     */
    public static String getUserIdFromCookie(GatewayOriginalRecord originalRecord) {
        if(originalRecord != null ){
            String userId = originalRecord.tracker_user_id();
            if(userId != null && userId.length() > 10){
//                tracker_invoke_count ++;
                return userId;
            }
        }
        return null;
    }

    /**
     * 先从cookie中获取用户id，如果没有再调用用户服务的接口
     * @param session_id
     * @param originalRecord
     * @return
     */
    public static String getUserId(String session_id,GatewayOriginalRecord originalRecord) {
        String userId = getUserIdFromCookie(originalRecord);

        if(userId != null ){
            return userId;
        }

        User user = getUserInfo(session_id);
        if (user != null) {
//            dubbo_invoke_count++;
            return user.getId();
        } else {
            return "";
        }
    }

    private static CookieDecoder cookieDecoder = new CookieDecoder();
    public static String getSessionId(GatewayOriginalRecord gatewayOriginalRecord) {
        // 183.199.206.248
        // 07/Nov/2018:13:42:13 +0800
        // 8445185aa9a34d4d9df67319a8128baf
        // service.eqxiu.com
        // POST
        // /login
        // -
        // password=abcd3324317&rememberMe=true&username=cuixiao
        // 200
        // Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36
        // http://www.eqxiu.com/auth/login?t=1541569323869
        // 0.203
        // 10.0.3.221:80
        // 200
        // 0.203
        // 385
        // -
        // JSESSIONID=8445185aa9a34d4d9df67319a8128baf; Domain=.eqxiu.com; Path=/; Max-Age=604800; Expires=Wed, 14-Nov-2018 05:42:13 GMT; HttpOnly

        String session_id = gatewayOriginalRecord.cookie_JSESSIONID();
        String request_args = gatewayOriginalRecord.args();
        String request_body = gatewayOriginalRecord.request_body();
        String response_cookie = gatewayOriginalRecord.upstream_http_set_cookie();

        if ("-".equals(session_id))
            session_id = "";
        if ("-".equals(request_args))
            request_args = "";
        if ("-".equals(request_body))
            request_body = "";
        if ("-".equals(response_cookie))
            response_cookie = "";

        // 1. 从 response_cookie 里解析JSESSIONID 作为 SESSION ID
        // 2. 取 session_id 作为 SESSION ID
        // 3. 从 request_args 里解析 jsessionid 作为 SESSION ID
        // 4. 从 request_body 里解析 jsessionid 作为 SESSION ID

        String session = "";

        try {
            // 1.
            for (Cookie cookie : cookieDecoder.decode(response_cookie)) {
                if ("JSESSIONID".equals(cookie.getName())) {
                    session = cookie.getValue();
                    break;
                }
            }
            if (session.length() > 10)
                return session;

            // 2.
            session = session_id;
            if (session.length() > 10)
                return session;

            // 3.
            QueryStringDecoder queryStringDecoder = new QueryStringDecoder(request_args.replace("\"", ""));
            List<String> jsessionid = queryStringDecoder.getParameters().get("jsessionid");
            if (jsessionid != null && jsessionid.size() > 0)
                session = jsessionid.get(0);
            if (session.length() > 10)
                return session;

            // 4.
            QueryStringDecoder queryStringDecoder2 = new QueryStringDecoder(request_body.replace("\"", ""));
            List<String> jsessionid2 = queryStringDecoder2.getParameters().get("jsessionid");
            if (jsessionid2 != null && jsessionid2.size() > 0)
                session = jsessionid2.get(0);
            if (session.length() > 10)
                return session;

        } catch (Exception e) {
            logger.error("获取 session id 失败：" + e.getMessage());
            logger.error("session_id -> " + session_id + ", request_args -> " + request_args + ", request_body -> " + request_body + ", response_cookie -> " + response_cookie);
        }

        return "";
    }


}
